/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Server.GUI;

import Server.BUS.QueryBUS;
import Server.BUS.QueryBUS_Update;
import Server.BUS.StringUlti;
import Server.DAO.DatabaseAccess;
import Server.DTO.*;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JOptionPane;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Trung
 */
public class QueryForm extends javax.swing.JPanel {

    /**
     * Creates new form QueryForm
     */
    JTabbedPane tabPane;
    
    Query query = null;
    QueryBUS queryBus = new QueryBUS();
    Database currentDB = new Database();
    List<Database> lstDB = new ArrayList<Database>();
    DatabaseAccess dbAccess = new DatabaseAccess();
    QueryBUS_Update queryUpdate=null;
    
    DefaultTableModel model = new DefaultTableModel();
    
    public QueryForm(List<Database> _lstDB, JTabbedPane _tabPane) {
        initComponents();
        
        this.lstDB = _lstDB;
        this.tabPane = _tabPane;
        //this.res_Table = new JTable(model);
        
        for(int i = 0; i < lstDB.size(); i++)
        {
            cbb_database.addItem(lstDB.get(i).getName());
        }
        int item = cbb_database.getSelectedIndex();
        if(item != -1)
        {
            currentDB = lstDB.get(item);
        }
        else
        {
            currentDB = null;
        }
        
        cbb_database.addItemListener(new ItemListener() {
        
            @Override
            public void itemStateChanged(ItemEvent e) {
                int item = cbb_database.getSelectedIndex();
                currentDB = lstDB.get(item);
            }
    });
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        cbb_database = new javax.swing.JComboBox();
        jLabel1 = new javax.swing.JLabel();
        jTabbedPane1 = new javax.swing.JTabbedPane();
        jPanel3 = new javax.swing.JPanel();
        res_ScrollPane = new javax.swing.JScrollPane();
        res_Table = new javax.swing.JTable();
        jPanel4 = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        ta_message = new javax.swing.JTextArea();
        bt_Clear = new javax.swing.JButton();
        bt_Excute = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        ta_queryInput = new javax.swing.JTextArea();

        jLabel1.setText("Database:");

        res_Table.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {

            }
        ));
        res_ScrollPane.setViewportView(res_Table);

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(res_ScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 646, Short.MAX_VALUE)
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(res_ScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 118, Short.MAX_VALUE)
        );

        jTabbedPane1.addTab("Results", jPanel3);

        ta_message.setColumns(20);
        ta_message.setRows(5);
        jScrollPane2.setViewportView(ta_message);

        javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
        jPanel4.setLayout(jPanel4Layout);
        jPanel4Layout.setHorizontalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 646, Short.MAX_VALUE)
        );
        jPanel4Layout.setVerticalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 118, Short.MAX_VALUE)
        );

        jTabbedPane1.addTab("Messages", jPanel4);

        bt_Clear.setText("Clear");

        bt_Excute.setText("Excute");
        bt_Excute.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bt_ExcuteActionPerformed(evt);
            }
        });

        ta_queryInput.setColumns(20);
        ta_queryInput.setRows(5);
        jScrollPane1.setViewportView(ta_queryInput);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(24, 24, 24)
                        .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 59, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(cbb_database, javax.swing.GroupLayout.PREFERRED_SIZE, 144, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jTabbedPane1))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(bt_Excute, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(bt_Clear, javax.swing.GroupLayout.PREFERRED_SIZE, 65, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jScrollPane1)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cbb_database, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 34, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(bt_Excute)
                        .addGap(18, 18, 18)
                        .addComponent(bt_Clear)))
                .addGap(18, 18, 18)
                .addComponent(jTabbedPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 146, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
    }// </editor-fold>//GEN-END:initComponents

    private void bt_ExcuteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bt_ExcuteActionPerformed
        // TODO add your handling code here:
        if(currentDB != null)
        {
            ((DefaultTableModel)res_Table.getModel()).setColumnCount(0);
            ((DefaultTableModel)res_Table.getModel()).setRowCount(0);        
            String queryString = ta_queryInput.getText();
            queryString = StringUlti.formatString(queryString);
            ta_message.setText("");

            switch (queryBus.checkQueryType(queryString)) {
                case SELECT_NOWHERE:
                    query = new SelectNoWhereQuery(queryString);
                    model = queryBus.selectNoWhereExecute(currentDB, (SelectNoWhereQuery)query); 
                    res_Table.setModel(model);
                    res_Table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
                    if(QueryBUS.SELECT_RESULT == 1)
                    {
                        this.ta_message.setText("Table(s) not exist in Database");
                    }
                    else
                        if(QueryBUS.SELECT_RESULT == 2)
                        {

                            this.ta_message.setText("Column(s) not exist in Tables list");
                        }
                    break;
                case SELECT_HAVEWHERE:
                    query = new SelectHaveWhereQuery(queryString);
                    break;
                case INSERT:
                    query = new InsertQuery(queryString);
                    if(queryBus.insertExecute(currentDB, (InsertQuery)query) == 0)
                    {
                        ta_message.setText("insert 1 row success");
                    }
                    else
                    {
                        if(queryBus.insertExecute(currentDB, (InsertQuery)query) == 1)
                            ta_message.setText("Can't find the Table in Database");
                        else
                        {
                            if(queryBus.insertExecute(currentDB, (InsertQuery)query) == 2)
                                ta_message.setText("The properties are primary key or not alllow null not found");
                            else
                                ta_message.setText("DataType not appropriate");
                        }
                    }
                    break;
                case DELETE_NOWHERE:
                    queryUpdate=new QueryBUS_Update(ta_queryInput.getText());
                    queryUpdate.executeDeleteToXMLNoWhere(currentDB);
                    break;
                case DELETE_HAVEWHERE:
                    queryUpdate=new QueryBUS_Update(ta_queryInput.getText());
                    queryUpdate.executeDeleteToXMLHaveWhere(currentDB,queryUpdate.getlstWhereDelete());
                    break;
                case UPDATE_NOWHERE:
                    queryUpdate=new QueryBUS_Update(ta_queryInput.getText());
                    queryUpdate.executeUpdateToXMLNoWhere(currentDB, queryUpdate.getLstSet());
                    break;
                case UPDATE_HAVEWHERE:
                    queryUpdate=new QueryBUS_Update(ta_queryInput.getText());
                    queryUpdate.executeUpdatetoXMLHaveWhere(currentDB, queryUpdate.GetIDRowUpdate(queryUpdate.getWhereExpressionUpdate(), currentDB), queryUpdate.getLstSet());
                    break;
                case INVALID_QUERY:
                    this.ta_message.setText("Query String invalid!");
                    break;
            }   
        }
        else
            JOptionPane.showMessageDialog(tabPane, "Current Database is null");

    }//GEN-LAST:event_bt_ExcuteActionPerformed
    public void execute() 
    {
    }
    
    public void insertExecute()
    {
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton bt_Clear;
    private javax.swing.JButton bt_Excute;
    private javax.swing.JComboBox cbb_database;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTabbedPane jTabbedPane1;
    private javax.swing.JScrollPane res_ScrollPane;
    private javax.swing.JTable res_Table;
    private javax.swing.JTextArea ta_message;
    private javax.swing.JTextArea ta_queryInput;
    // End of variables declaration//GEN-END:variables
}
